const { parentPort, workerData } = require('worker_threads')
import { addUserTask, initializeDatabase } from './database'

// 从workerData中获取数据
const { dbPath } = workerData
console.log(`BatchTaskWorker: 初始化数据库，路径为 ${dbPath}`)
let db = null
let GoodInfoApi = 'http://127.0.0.1:9992/taobao/detail'

try {
  db = initializeDatabase(dbPath)
  console.log('BatchTaskWorker: 数据库初始化成功')
} catch (error) {
  console.error('BatchTaskWorker: 数据库初始化失败', error)
  // 向主线程发送初始化失败的消息
  parentPort.postMessage({
    success: false,
    error: `数据库初始化失败: ${error.message}`
  })
}

// 🚀 每批发送 10 个请求
const BATCH_SIZE = 1
async function fetchInBatches(userId, urls, taskId, mb) {
  const results = []

  for (let i = 0; i < urls.length; i += BATCH_SIZE) {
    const batchUrls = urls.slice(i, i + BATCH_SIZE)
    // https://detail.tmall.com/item.htm?id=729760922712
    // getAllUrlParams().id
    const batchPromises = batchUrls.map((url) => {
      const id = getAllUrlParams(url).id
      return fetch(`${GoodInfoApi}?itemId=${id}`).then((res) => {
        return res.json().then((json) => {
          return {
            id,
            result: JSON.stringify(json),
            userId,
            taskId,
            mb,
            task_url: url
          }
        })
      })
    })
    try {
      const batchResults = await Promise.all(batchPromises)
      results.push(...batchResults)
      console.log(`用户${userId} 批次 ${i / BATCH_SIZE + 1} 完成！`)
    } catch (err) {
      console.error(`用户${userId} 批次 ${i / BATCH_SIZE + 1} 失败：`, err)
    }
  }

  return results
}

// worker.js
// 监听主线程消息
parentPort.onmessage = async function (e) {
  const { id, value } = e.data
  console.log(`接收到主线程消息 - Worker ID: ${id}, 数据:`, value)

  try {
    // 调用计算函数，传递workerId和输入数据
    const result = await heavyCalculation(id, value)

    // 返回结果和ID以便主线程识别
    parentPort.postMessage({ id, result, success: true })
    // console.log(`Worker ${id}: 计算成功，结果:`, result)
  } catch (error) {
    console.error(`Worker ${id}: 计算失败`, error)
    parentPort.postMessage({ id, error: error.message, success: false })
  }
}

async function heavyCalculation(workerId, input) {
  let restlt = await fetchInBatches(input.userId, input.urls, input.taskId, input.mb)
  return restlt
}

function getAllUrlParams(url) {
  const queryIndex = url.indexOf('?')
  const hashIndex = url.indexOf('#')

  let queryString = ''
  if (queryIndex > -1) {
    queryString =
      hashIndex > queryIndex ? url.slice(queryIndex + 1, hashIndex) : url.slice(queryIndex + 1)
  }

  const hashString = hashIndex > -1 ? url.slice(hashIndex + 1) : ''

  const params = {}
  const queryParams = new URLSearchParams(queryString)
  const hashParams = new URLSearchParams(hashString)

  queryParams.forEach((val, key) => (params[key] = val))
  hashParams.forEach((val, key) => (params[key] = val))

  return params
}
